# coding=utf-8


from collections import defaultdict
import json
import requests

import pandas as pd


class PatientDataDownloader:

    gender_dict = {
        1: "男",
        2: "女"
    }

    def __init__(self, url=None):
        if not url:
            self.url = "https://host_example/api/v1/patient/search-config"
        else:
            self.url = url

        self.data = defaultdict(list)
        self.info_list = []
        self.header = {
            "Authorization": "",
            "Origin": "https://weien.linkedcare.cn",
            "Referer": "https://weien.linkedcare.cn/app-new/",
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0",
        }

        self.param = {
            "pageIndex": 1,
            "pageSize": 20,
            "searchText": "",
            "searchConfig": {
                "searchType": "患者查询",
                "name": "患者查询",
                "userId": 2127,
                "isShowWeiXin": None,
                "isAscending": False,
                "orderByField": "p.Id",
                "searchCondFields": [],
                "searchResultFields": [
                    {"code": "Name"},
                    {"code": "PrivateId"},
                    {"code": "PatientType"},
                    {"code": "Sex"},
                    {"code": "Age"},
                    {"code": "SourceType"},
                    {"code": "MembershipType"},
                    {"code": "RecordCreatedTime"},
                    {"code": "RecordCreatedUserName"},
                    {"code": "PatientTag"},
                    {"code": "PrivateTag"},
                    {"code": "Mobile"},
                    {"code": "Age"},
                    {"code": "Sex"},
                    {"code": "Name"},
                    {"code": "PrivateId"},
                    {"code": "SourceType"}
                ]
            }
        }

    def get_data(self, page_index, page_size):
        self.param["pageIndex"] = page_index
        self.param["pageSize"] = page_size
        res = requests.put(self.url, json=self.param, headers=self.header)
        # import pdb; pdb.set_trace()
        if res.status_code != requests.codes.ok:
            raise ValueError("request fails")
        # print(res.text)
        content = res.content
        return json.loads(content)

    def format(self, item):
        # import pdb; pdb.set_trace()
        self.data["患者姓名"].append(item.get("name"))
        self.data["病例号"].append(item.get("privateId"))

        self.data["生日"].append(item.get("birth"))
        self.data["联系方式"].append(item.get("mobile"))
        self.data["患者类型"].append(item.get("patientType"))
        self.data["一级来源"].append(item.get("sourceTypeOne"))
        self.data["二级来源"].append(item.get("sourceTypeTwo"))

        self.data["欠费金额"].append(item.get("overdue"))

        gender = self.gender_dict.get(item.get("sex"))
        if not gender:
            gender = "未填写"
        self.data["性别"].append(gender)

        self.data["三级来源-推荐人"].append(item.get("refereeName"))
        self.data["创建时间"].append(item.get("recordCreatedTime"))
        self.data["创建人 id"].append(item.get("recordCreatedUser"))
        self.data["创建人名字"].append(item.get("recordCreatedUserName"))

    def save(self):
        page_index = 1
        page_size = 20
        while True:
            res = p.get_data(page_index, page_size)
            # import pdb; pdb.set_trace()

            infos = res.get("items")
            if not infos:
                break

            for item in infos:
                self.format(item)
            page_index += 1

        print(self.data)
        df = pd.DataFrame(self.data)
        df.to_excel('患者数据.xlsx', index=False)


if __name__ == "__main__":
    p = PatientDataDownloader()
    p.save()

